package com.readygo.boot_test.service.auth;

import com.readygo.boot_test.entity.auth.Role;
import com.readygo.boot_test.entity.auth.RoleKey;
import com.readygo.boot_test.entity.auth.SecurityUser;
import com.readygo.boot_test.repository.auth.RoleRepository;
import com.readygo.boot_test.repository.auth.SecurityUserRepository;
import com.readygo.boot_test.request.AddSecurityUserRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SecurityUserService {

    private SecurityUserRepository securityUserRepository;

    private RoleRepository roleRepository;

    private BCryptPasswordEncoder passwordEncoder;


    @Autowired
    public SecurityUserService(SecurityUserRepository securityUserRepository, RoleRepository roleRepository,
                               BCryptPasswordEncoder passwordEncoder) {
        this.securityUserRepository = securityUserRepository;
        this.roleRepository = roleRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Transactional
    public SecurityUser save(AddSecurityUserRequest request) {

        if (request == null) {
            return null;
        }

        SecurityUser securityUser = new SecurityUser();
        BeanUtils.copyProperties(request, securityUser);
        securityUser.setPassword(passwordEncoder.encode(securityUser.getPassword()));
        securityUser.setAccountNonExpired(true);
        securityUser.setAccountNonLocked(true);
        securityUser.setCredentialsNonExpired(true);
        securityUser.setEnabled(true);

        securityUser = securityUserRepository.save(securityUser);
        String[] roles = StringUtils.commaDelimitedListToStringArray(request.getRoles());;
        final Integer securityUserId = securityUser.getSecurityUserId();
        if (roles.length > 0) {
            List<Role> roleList = new ArrayList<>();
            Arrays.asList(roles).forEach(role -> {
                Role entity = new Role();
                RoleKey roleKey = new RoleKey();
                roleKey.setSecurityUserId(securityUserId);
                roleKey.setRole(role);
                entity.setRoleKey(roleKey);
                roleList.add(entity);
            });
            roleRepository.save(roleList);
        }

        return securityUser;
    }

}
